package com.bpzj.util.validation;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Created by bpzj on 2019-9-1.
 */
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {ChinaPersonIdCardValidator.class})
public @interface ChinaPersonIdCard {

  // todo 代码注释 含义

  /**
   * 默认：不允许为空
   */
  Flag[] flags() default {Flag.NOT_EMPTY};

  String message() default "无效的身份证号码";

  String regexp() default
      "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))([0-2][1-9]|10|20|30|31)\\d{3}[0-9Xx]$)"
          + "|(^[1-9]\\d{5}\\d{2}(0[0-9]|10|11|12)(([0-2][1-9])|10|20|30|31)\\d{3}$)";

  /**
   * @return the groups the constraint belongs to 约束注解在验证时所属的组别
   */
  Class<?>[] groups() default {};

  Class<? extends Payload>[] payload() default {};

  @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
  @Retention(RUNTIME)
  @Documented
  @interface List {
    ChinaPersonIdCard[] value();
  }

  /** 通过改变 flag 的值，改变 regexp 允许的值*/
  public static enum Flag {

      /**
       * 不允许为空 或 null 必填
       */
      NOT_EMPTY(0),

      /**
       * 允许空字符
       */
      ALLOW_EMPTY(1),

      /**
       * 允许 null
       */
      ALLOW_NULL(2),
      ;

      private final int value;

      Flag(int value) {
        this.value = value;
      }

      public int getValue() {
        return value;
      }
  }
}
